package cn.com.hhrcw.web;

import cn.com.hhrcw.entity.EnInfo;
import cn.com.hhrcw.entity.OpDeliveryHistory;
import cn.com.hhrcw.entity.OpJob;
import cn.com.hhrcw.entity.SsSession;
import cn.com.hhrcw.mapstruct.OpJobConvert;
import cn.com.hhrcw.mapstruct.SsSessionConvert;
import cn.com.hhrcw.params.PersonalJobParams;
import cn.com.hhrcw.params.SsSessionParams;
import cn.com.hhrcw.service.IEnInfoService;
import cn.com.hhrcw.service.IOpDeliveryHistoryService;
import cn.com.hhrcw.service.IOpJobService;
import cn.com.hhrcw.service.ISsSessionService;
import cn.com.hhrcw.vo.OpJobVO;
import cn.com.hhrcw.vo.ParticipationNumberVO;
import cn.com.hhrcw.vo.SsSessionVO;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.base.entity.AttributesValueParams;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Function;

/**
 * 专场-专场本场
 *
 * @author jiangdong
 * @since 2020-10-29
 */
@RestController
@Slf4j
@RequestMapping("/personal/ssSession")
@Api(tags = "专场-专场本场")
@Validated
public class SsSessionController extends JeecgController<SsSession, ISsSessionService> {

    @Autowired
    private ISsSessionService ssSessionService;

    @Autowired
    private SsSessionConvert ssSessionConvert;
    @Autowired
    private IOpJobService jobService;
    @Autowired
    private IOpDeliveryHistoryService deliveryHistoryService;
    @Autowired
    private OpJobConvert jobConvert;
    @Autowired
    private IEnInfoService enInfoService;

    private static int viewers =  1483;

    private static int addCount =  0;


    /**
     * 专场招聘-专场列表
     *
     * @param params 请求参数
     * @return
     */
    @GetMapping(value = "/list")
    @AutoLog("专场-专场本场-分页列表查询")
    @ApiOperation(value = "分页列表查询", notes = "分页列表查询")
    public Result<Page<SsSessionVO>> list(  SsSessionParams params) {
        LambdaQueryWrapper<SsSession> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SsSession::getDelFlag, false);
        Date date = new Date();
        if (StringUtils.isNotBlank(params.getTitle())){
            queryWrapper.like(SsSession::getTitle, params.getTitle());
        }
        queryWrapper.eq(SsSession::getPubFlag,1);

        IPage<SsSession> page = ssSessionService.page(params.page(), queryWrapper);
        //分页结果转换器
        Function<SsSession, SsSessionVO> fun = ssSession -> {
            SsSessionVO vo = ssSessionConvert.toVO(ssSession);

            //职位数量
            LambdaQueryWrapper<OpJob> jobQuery = new LambdaQueryWrapper<>();
            jobQuery.eq(OpJob::getDelFlag, false).eq(OpJob::getBsType, 1).eq(OpJob::getBsId, vo.getId()).select(OpJob::getId);
            List<OpJob> job = jobService.list(jobQuery);
            Set<String> companyIds = new HashSet<>();
            if (!CollectionUtils.isEmpty(job)) {
                vo.setJobCount(job.size());
                List<String> jobIds = new ArrayList<>();
                job.forEach(e -> {
                    companyIds.add(e.getCompanyId());
                    jobIds.add(e.getId());
                });
                LambdaQueryWrapper<OpDeliveryHistory> historyQuery = new LambdaQueryWrapper<>();
                historyQuery.eq(OpDeliveryHistory::getDelFlag, false).in(OpDeliveryHistory::getJobId, jobIds);
                int deliveryCount = deliveryHistoryService.count(historyQuery);
                vo.setUserCount(deliveryCount);
                vo.setCompanyCount(companyIds.size());
            }
            return vo;
        };
        return Result.ok((Page) page.convert(fun));
    }

    /**
     * 专场招聘-职位
     *
     * @param params  专场id必传
     * @param request
     * @return
     */
    @GetMapping("/getJobList")
    public Result<Page<OpJobVO>> getJobListBySessionId(@RequestBody @Valid PersonalJobParams params, HttpServletRequest request) {

        LambdaQueryWrapper<OpJob> jobQuery = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(params.getName())) {
            LambdaQueryWrapper<EnInfo> enQuery = new LambdaQueryWrapper<>();
            enQuery.like(EnInfo::getEnName, params.getName()).eq(EnInfo::getDelFlag, false);
            List<EnInfo> list = enInfoService.list(enQuery);
            if (!CollectionUtils.isEmpty(list)) {
                jobQuery.and(wrapper -> wrapper.like(OpJob::getJobName, params.getName()).or().in(OpJob::getCompanyId, list));
            } else {
                jobQuery.like(OpJob::getJobName, params.getName());
            }
        }
        if (StringUtils.isNotBlank(params.getPersonlRange())) {
            LambdaQueryWrapper<EnInfo> enQuery = new LambdaQueryWrapper<>();
            enQuery.like(EnInfo::getEnPersonnel, params.getPersonlRange()).eq(EnInfo::getDelFlag, false);
            List<EnInfo> list = enInfoService.list(enQuery);
            if (!CollectionUtils.isEmpty(list)) {
                jobQuery.in(OpJob::getCompanyId, list);
            } else {
                jobQuery.in(OpJob::getCompanyId, "");
            }
        }
        if (StringUtils.isNotBlank(params.getEduLevel())) {
            jobQuery.like(OpJob::getEduLevel, params.getEduLevel());
        }
        if (StringUtils.isNotBlank(params.getTrade())) {
            LambdaQueryWrapper<EnInfo> enQuery = new LambdaQueryWrapper<>();
            enQuery.like(EnInfo::getEnTrade, params.getTrade()).eq(EnInfo::getDelFlag, false);
            List<EnInfo> list = enInfoService.list(enQuery);
            if (!CollectionUtils.isEmpty(list)) {
                jobQuery.in(OpJob::getCompanyId, list);
            } else {
                jobQuery.in(OpJob::getCompanyId, "");
            }
        }
        jobQuery.eq(OpJob::getDelFlag, false).eq(OpJob::getBsType, 1).eq(OpJob::getBsId, params.getId());
        IPage<OpJob> page = jobService.page(params.page(), jobQuery);
        Function<OpJob, OpJobVO> fun = job -> {
            OpJobVO vo = jobConvert.toVO(job);
            return vo;
        };
        return Result.ok((Page) page.convert(fun));
    }

    /**
     * 专场根据id查询
     *
     * @param id 数据id
     * @return
     */
    @GetMapping(value = "/queryById")
    @ApiOperation(value = "根据id查询", notes = "根据id查询")
    public Result<?> queryById(String id) {
        SsSession ssSession = ssSessionService
                .lambdaQuery()
                .eq(SsSession::getId, id)
                .eq(SsSession::getDelFlag, false)
                .one();
        if (ssSession == null) {
            return Result.error(404,"数据不存在");
        }
        return Result.ok(ssSessionConvert.toVO(ssSession));
    }

    /**
     * 专场根据id查询参与明细
     *
     * @param id 数据id
     * @return
     */
    @GetMapping(value = "/queryDetailNumById")
    @ApiOperation(value = "根据id查询", notes = "根据id查询")
    public Result<?> queryDetailNumById(String id) {
        ParticipationNumberVO vo = new ParticipationNumberVO();
        List<OpJob> list = jobService.lambdaQuery()
            .eq(OpJob::getDelFlag,false)
            .eq(OpJob::getBsType,1)
            .eq(OpJob::getBsId,id).list();
        if(CollectionUtils.isEmpty(list)) return Result.ok(vo);
        Set<String> companySet = new HashSet<>();
        list.forEach(x -> {
            companySet.add(x.getCompanyId());
        });
        vo.setCompanies(companySet.size());
        vo.setJobs(list.size());
        addCount ++;
        if(addCount % 8 == 0) {
            viewers ++;
        }
        vo.setViewers(viewers);
        return Result.ok(vo);
    }

    /**
     * 添加
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/add")
    @AutoLog("专场-专场本场-添加")
    @ApiOperation(value = "添加", notes = "添加")
    @RequiresPermissions("ssSession:add")
    public Result<?> add(@RequestBody @Valid SsSessionParams params) {

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SsSession ssSession = ssSessionConvert.toEntity(params);
        ssSession.setCreateBy(sysUser.getId());
        ssSession.setCreateTime(DateUtil.date());
        ssSession.setDelFlag(false);

        //ssSession.setNo(super.sort("ss_session", Constant.NO_SEED));//FIXME: 编号,可根据情况隐藏
        boolean saved = ssSessionService.save(ssSession);
        return saved ? Result.ok() : Result.error("添加失败");
    }

    /**
     * 编辑
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/edit")
    @AutoLog("专场-专场本场-编辑")
    @ApiOperation(value = "编辑", notes = "编辑")
    @RequiresPermissions("ssSession:edit")
    public Result<?> edit(@RequestBody @Valid SsSessionParams params) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        SsSession ssSession = ssSessionConvert.toEntity(params);
        ssSession.setUpdateBy(sysUser.getId());
        ssSession.setUpdateTime(DateUtil.date());

        boolean updated = ssSessionService.updateById(ssSession);
        return updated ? Result.ok() : Result.error("编辑失败");
    }


    /**
     * 批量删除
     *
     * @param id 数据id
     * @return
     */
    @GetMapping(value = "/delete")
    @AutoLog("专场-专场本场-批量删除")
    @ApiOperation(value = "批量删除", notes = "批量删除")
    @RequiresPermissions("ssSession:delete")
    public Result delete(String[] id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        LambdaUpdateWrapper<SsSession> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.in(SsSession::getId, id)
                .set(SsSession::getDelFlag, true)
                .set(SsSession::getUpdateBy, sysUser.getUsername())
                .set(SsSession::getUpdateTime, DateUtil.date());

        boolean deleted = ssSessionService.update(updateWrapper);
        return deleted ? Result.ok() : Result.error("删除失败");
    }

    /**
     * 属性值是否重复
     *
     * @return
     */
    @Override
    @GetMapping("/propertyRepeat")
    @ApiOperation(value = "属性值是否重复", notes = "属性值是否重复")
    public Result propertyIsRepeat(@Valid AttributesValueParams params) {
        return super.propertyIsRepeat(params);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param params
     */
    @SneakyThrows
    @GetMapping(value = "/exportXls")
    @ApiOperation(value = "导出excel", notes = "导出excel")
    public Result exportXls(HttpServletRequest request, SsSessionParams params) {
        SsSession ssSession = ssSessionConvert.toEntity(params);
        ssSession.setDelFlag(false);
        QueryWrapper<SsSession> queryWrapper = QueryGenerator.initQueryWrapper(ssSession, request.getParameterMap());
        List<SsSession> data = ssSessionService.list(queryWrapper);
        ExportParams exportParams = new ExportParams("专场-专场本场", "专场-专场本场");
        String url = super.exportXls(exportParams, SsSessionVO.class, ssSessionConvert.toVO(data));
        return Result.ok((Object) url);
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "/importExcel")
    @ApiOperation(value = "通过excel导入数据", notes = "通过excel导入数据")
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, SsSession.class);
    }

}
